# coding: utf-8
from typing import Callable

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget, QVBoxLayout, QLayout
from qfluentwidgets import SingleDirectionScrollArea, StateToolTip

from common import WorkerThread, worker_result
from .alert import Alert


class CustomScrollArea(SingleDirectionScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.workerThread = WorkerThread(self)
        self.stateToolTip = StateToolTip('加载中', '正在加载，请稍后...', self)

        self.setObjectName('CustomScrollArea')
        self.setWidgetResizable(True)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)

        self.stateToolTip.hide()

        self.workerThread.result.connect(worker_result)
        self.workerThread.error.connect(Alert.error)
        self.workerThread.started.connect(self.stateToolTip.show)
        self.workerThread.finished.connect(self.stateToolTip.hide)

    def setWidget(self, widget: QWidget):
        widget.setAutoFillBackground(False)
        super().setWidget(widget)
        self.enableTransparentBackground()

    def setSpacing(self, spacing: int):
        self.widget().layout().setSpacing(spacing)

    def setLayoutContentsMargins(self, left: int, top: int, right: int, bottom: int):
        self.widget().layout().setContentsMargins(left, top, right, bottom)

    def addWidget(self, widget: QWidget, *args, **kwargs):
        self.widget().layout().addWidget(widget, *args, **kwargs)

    def addLayout(self, layout: QLayout, stretch: int = 1):
        self.widget().layout().addLayout(layout, stretch)

    def addSpacing(self, spacing: int):
        self.widget().layout().addSpacing(spacing)

    def addStretch(self, stretch: int = 0):
        self.widget().layout().addStretch(stretch)

    def removeWidget(self, widget: QWidget):
        self.widget().layout().removeWidget(widget)

    def load(self, func: Callable, *args, slot: Callable = None, **kwargs):
        self.workerThread.addTask(func, *args, slot=slot, **kwargs)

    def resizeEvent(self, event):
        self.stateToolTip.move(self.width() - self.stateToolTip.width() - 20, 20)
        super().resizeEvent(event)


class ViewScrollArea(CustomScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.view = QWidget()

        self.setWidget(self.view)
        self.setObjectName('ViewScrollArea')


class VerticalScrollArea(ViewScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self.view)
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)

        self.setObjectName('VerticalScrollArea')
        self.view.setLayout(self.verticalLayout)
